from symtable import Class

from python.day3.demo9_sum_score import split

words = ["java", "java", "java", "java", "hadoop", "python"]
classs = ["文科一班", "文科一班", "文科一班", "文科二班", "文科二班"]


# 封装函数，计算每个元素出现的数量
# 如果一段代码逻辑出现了多次，那么就可以将这段代码逻辑封装成函数，将代码逻辑中需要改变的变量作为参数传递给函数
def count(data):
    # 循环统计每个元素出现的次数
    count_num = {}
    for i in data:
        if i not in count_num:
            count_num[i] = 1
        else:
            count_num[i] += 1
    return count_num


# 多次使用函数进行统计
word_count = count(words)
print(word_count)

clazz_num = count(classs)
print(clazz_num)


# 定义读取文件的函数
def read_file(file_path, encoding='utf-8'):
    with open(file=file_path, mode='r', encoding=encoding) as f:
        lines = f.readlines()

        # 去掉每一行后面的换行符
        new_lines = []
        for line in lines:
            new_lines.append(line.strip())

        return new_lines


students = read_file("../../data/student.txt")
print(students)

lines = read_file("../../data/lines.txt")
print(lines)


# 定义保存文件的函数
def save_file(file_path, data, encoding='utf-8'):
    with open(file=file_path, mode='w', encoding=encoding) as f:
        for key, value in data.items():
            f.write(f"{key},{value}\n")


# 使用函数
save_file("../../data/word_count.txt", word_count)
save_file("../../data/clazz_num.txt", clazz_num)

# 使用上面定义的函数进行停机

# 统计性别的人数
# 1、读取文件
students = read_file("../../data/student.txt")
print(students)

# 2、获取性别
sexs = []
for student in students:
    sex = student.split(",")[3]
    sexs.append(sex)
print(sexs)

# 3、统计性别的人数
sex_num = count(sexs)
print(sex_num)

# 4、将结果保存到文件中
save_file("../../data/sex_num.txt", sex_num)


# 封装函数从学生表中获取字段
def map(data, index, sep=","):
    new_data = []
    for item in data:
        i = item.split(sep)[index]
        new_data.append(i)
    return new_data


# 统计年龄二点人数
# 1、读取数据
students = read_file("../../data/student.txt")
# 2、取出年龄
ages = map(students, 2)
# 3、统计年龄的人数
age_num = count(ages)
# 4、保存到文件
save_file("../../data/age_num.txt", age_num)
